package com.cskaoyan.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.boot.autoconfigure.batch.BatchProperties;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author stone
 * @date 2022/09/07 10:54
 */
// 当数据库中的列和引用类型中的成员变量是对应的类型的时候，会自动使用TypeHandler
@MappedTypes(Integer[].class)//java类型
@MappedJdbcTypes(JdbcType.VARCHAR)//数据库类型
public class IntegerArrayTypeHandler implements TypeHandler<Integer[]> {
    ObjectMapper objectMapper = new ObjectMapper();

    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Integer[] integers, JdbcType jdbcType) throws SQLException {
        String value = objectMapper.writeValueAsString(integers);//也可以用Gson
        preparedStatement.setString(i, value);
    }

    @Override
    public Integer[] getResult(ResultSet resultSet, String columnName) throws SQLException {
        String result = resultSet.getString(columnName);
        return transfer(result);
    }

    @Override
    public Integer[] getResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String result = resultSet.getString(columnIndex);
        return transfer(result);
    }

    @Override
    public Integer[] getResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String result = callableStatement.getString(columnIndex);
        return transfer(result);
    }

    @SneakyThrows
    private Integer[] transfer(String result) {
        Integer[] array = new Integer[0];
        if (result == null || "".equals(result)) {
            return array;
        }
        array = objectMapper.readValue(result, Integer[].class);
        return array;
    }
}
